package com.bwie.goods.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Goods;
import com.bwie.common.domain.User;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.goods.mapper.GoodsMapper;
import com.bwie.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<Goods> findGoodList(Goods goods) {
        List<Goods> goodList = goodsMapper.findGoodList(goods);
        return goodList;
    }

    @Override
    public Result addGood(Goods goods) {
        String header = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(header);
        String userJSONStr = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        User user = JSONObject.parseObject(userJSONStr, User.class);
        goods.setCreatorId(user.getUserId());
        goods.setCreateTime(new Date());
        Integer flag = goodsMapper.addGood(goods);
        if(flag<=0){
            return Result.error("添加失败");
        }
        return Result.success("添加成功");
    }

    @Override
    public Result delGood(Integer id) {
        Integer flag = goodsMapper.delGood(id);
        if(flag<=0){
            return Result.error("删除失败");
        }
        return Result.success("删除成功");
    }

    @Override
    public List<Goods> findList() {
        List<Goods> list = goodsMapper.findList();
        return list;
    }
}
